package jdmx.library.utils;

public class LexicalFactory {
	protected Class<?> defaultType;
	protected String prefix;
	protected String suffix;
	
	public LexicalFactory(Class<?> defaultType, String prefix, String suffix) {
		this.defaultType = defaultType; 
		this.prefix = prefix;
		this.suffix = suffix;
	}
	
	public Object createInstance(String className, String namespace, Class<?> defaultType) {
		Class<?> type = null;
		if ( 
				(className != null) 
				&& (!className.equals(""))
				&& (namespace != null)
				&& (!namespace.equals(""))
				) 
		{
			String classFqn = namespace + "." + prefix + className + suffix;
			try {
				type =  Class.forName(classFqn);
			} catch (ClassNotFoundException e1) {
				//
			}
		}

		if (type == null) {
			Class<?> actualDefaultType = ((defaultType != null) ? defaultType : this.defaultType);
			type = actualDefaultType;
		}
		
		if (type == null) 
			return null;
		
		Object o = null;
		try {
			o = type.newInstance();
		} catch (InstantiationException e1) {
		} catch (IllegalAccessException e1) {
		}
		
		return o;
	}

	public Object createInstance(String className, String namespace) {
		return createInstance(className, namespace, null);
	}
}
